import {BadRequestException, Controller, Get, Post, Query, Req} from "@nestjs/common";
import {ApiBearerAuth, ApiBody, ApiConsumes, ApiOperation, ApiTags} from "@nestjs/swagger";
import {FastifyRequest} from 'fastify'
import {plainToInstance} from 'class-transformer'
import {validate} from 'class-validator'
import {Public} from "~/modules/auth/decorators/public.decorator";
import {AuthUser} from "~/modules/auth/decorators/auth-user.decorator";
import {AccessHouseUploadDto} from "~/modules/assess/house/house.dto";
import {AccessHouseService} from "~/modules/assess/house/house.service";

@ApiTags("House - 户型图评估")
@ApiBearerAuth()
@Controller('access/house')
export class HouseController {
  constructor(
    private readonly accessHouseService: AccessHouseService
  ) {
  }

  @Post("upload")
  @ApiOperation({summary: '上传户型评估'})
  @ApiConsumes('multipart/form-data')
  @ApiBody({type: AccessHouseUploadDto})
  async addAccess(@Req() req: FastifyRequest, @AuthUser() user: IAuthUser) {
    try {
      const params: Record<string, any> = req.body

      params.file = params.file[0]

      const accessUploadDto = plainToInstance(AccessHouseUploadDto, req.body)
      const errors = await validate(accessUploadDto)

      if (errors.length) {
        // 取出 errors[0].constraints 中的第一个错误信息，constraints为一个对象结构
        const message = Object.values(errors[0].constraints)[0]
        throw new BadRequestException(message)
      }

      // 业务逻辑
      return await this.accessHouseService.save(accessUploadDto, user.uid)
    }
    catch (error) {
      throw new BadRequestException(error?.message ?? '上传失败')
    }
  }

  @Get("list")
  @ApiOperation({summary: '获取评估列表'})
  async getAccess(@AuthUser() user: IAuthUser) {
    // 获取户型评估
    return await this.accessHouseService.getList(user.uid);
  }

	/**
	 * 根据id查询户型评估
	 */
	@Get('find')
	@ApiOperation({ summary: '根据id查询户型评估' })
	async find(@Query('id') id: string) {
		return await this.accessHouseService.find(Number(id))
	}
}
